/**
 * 客户资源录入脚本支持
 */
var nam ="";
var pho = "";
	//页面载入初始化
$( "body" ).ready( function( e )
{
	try
	{
		if( typeof ( eval( "init" ) ) == "function" )
			eval( "init();" );
	}
	catch( e )
	{
	}

	// 键盘事件
	$( "body" ).bind( "keyup", bodyKeyupHandler );

	// 初始化
	button_bind();
	init_editors();
	client_detailed( false );
} );

//--------------------------------------------------------------------------
//
//	consultant_client_first.php
//
//--------------------------------------------------------------------------

var _state_detailed = false;
var _editor = [];

function button_bind()
{
	$( "#btnSubmit" ).click( function(e){
		submit_form();
	});
	$( "#btn_detailed" ).click( function( e )
	{
		e.stopPropagation();
		_state_detailed = !_state_detailed;
		client_detailed( _state_detailed );
	} );

	$( "#btnAddCategory" ).click( function( e )
	{
		parent.adder.setCallback( submit_newCategory );
		parent.adder.open( "添加新客户类别", "类别名称：", "<em><b>说明</b>：请尽量精简保持在5个汉字以内，并且不要重复添加相同的类别名称。</em>" );
	} );

	$( "#btnAddSource" ).click( function( e )
	{
		parent.adder.setCallback( submit_newsource );
		parent.adder.open( "添加新客户来源渠道", "渠道名称：", "<em><b>说明</b>：请尽量精简保持在5个汉字以内，并且不要重复添加相同的渠道名称。</em>" );
	} );

	$( "#btnAddQuest" ).click( function()
	{
		quest_add( $( "#quest_list" ), "", "" );
	} );

	$( "#url" ).parent().parent().hide();
	$( "#source" ).change( function()
	{
		var tr = $( "#url" ).parent().parent();
		if( $( this ).val() == "pmvk5vdc6ity" )
		{
			tr.show();
		}
		else
		{
			tr.hide();
		}
	} );

	// 首次不开放添加状态，需要的话，由管理员操作
	//	$( "#btnAddState" ).click( function( e )
	//	{
	//		parent.adder.setCallback( submit_newstate );
	//		parent.adder.open( "添加新客户状态", "状态名称：", "<em><b>说明</b>：请尽量精简保持在5个汉字以内，并且不要重复添加相同的状态名称。</em>" );
	//	} );

	// 增加新学员
	$( "#btnAddStudent" ).click( function()
	{
		setNewStudent();

		// 添加ID到格式化对象库
		init_editors();

		// 更新背景
		update_row_bg();
	} );

	// 默认添加一个学员
	$( "#btnAddStudent" ).trigger( "click" );

}



function phone_repeat( v )
{
	$( "#phone" ).parent().find( "p[rel='errnote']" ).text( v.err == 1 ? "该号码已存在，勿重复添加客户资源。（登记人：" + v.reg + " - 负责人：" + v.chg + "）" : "" );
}
function qq_repeat( v )
{
	$( "#qq" ).parent().find( "p[rel='errnote']" ).text( v.err == 1 ? "该QQ已存在，勿重复添加客户资源。（登记人：" + v.reg + " - 负责人：" + v.chg + "）" : "" );
}
function email_repeat( v )
{
	$( "#email" ).parent().find( "p[rel='errnote']" ).text( v.err == 1 ? "该邮箱已存在，勿重复添加客户资源。（登记人：" + v.reg + " - 负责人：" + v.chg + "）" : "" );
}

function init_editors()
{
	$( "div[contenteditable='true']" ).each( function()
	{
		if( _editor.indexOf( $( this ).attr( "id" ) ) == -1 )
			_editor.push( $( this ).attr( "id" ) );
	} );
}

function client_detailed( visible )
{
	if( visible )
		$( "#infotable" ).find( "tr[rel='hide']" ).show();
	else
		$( "#infotable" ).find( "tr[rel='hide']" ).hide();
}

//--------------------------------------------------------------------------
//
//	数据提交
//
//--------------------------------------------------------------------------

 

function submit_newsource( arr )
{
	if(arr[0]==null || arr[0]==""){
		alert("渠道不能为空。");
		return;
	}
	$.post( contextPath+"/index/consultant_source_add_go.json", { name: arr[0], explain: arr[1] }, function( d )
	{
			$( "#source" ).append(
				"<option value='" + d.key + "' title='" + d.explain + "'>" + d.name + "</option>" );
			$( "#source" ).val( d.key );
	
	}, "json" );
}

/*function submit_newstate( arr )
{
	submitter.post( "consultant_state_add_go.php", { name: arr[ 0 ], explain: arr[ 1 ] }, function( d )
	{
		if( d.err == 0 )
		{
			infopad.msg( d.msg );

			$( "#statelist" )
				.append(
				"<label for='state_" + d.id + "' title='" + d.explain + "'><input id='state_"
				+ d.id + "' type='checkbox' value='" + d.key + "' checked='true'>"
				+ d.name + "</label>" );
		}
		else
		{
			infopad.err( d.msg );
		}
	}, "json" );
}*/
$(function(){
	$(".off_input").focusout(function(){
		if($(this).val()!=""){
			var name = $(this).attr('id');
			if(name=="phone"){
				if($(this).val()!== ""){
					if(!(/^1[0-9]{10}$/.test($(this).val()))){
						alert("输入的手机号码有误，请重新输入！");
						$("#btnSubmit").attr("disabled",false);
						return false;
					}else{
						$("#btnSubmit").attr("disabled",true);
						query_name(name,$(this).val());
					}
				}
			}else{
				query_name(name,$(this).val());
			}
			
		}
	});
});


function query_name(type,va){
	$.post( contextPath+"/index/query.json", {
		"type":type,"va":va,
	}, function( d ){
			var name = d.name;
			var nickname = d.user;
			var type = d.type;
			if(type=="phone"){
				$("#"+type).parent().parent().find( "p[rel='errnote']").html(" ");
			}else{
				$("#"+type).parent().find( "p[rel='errnote']").html(" ");
			}
			if(name!=null && nickname!=null){
				if(name == nickname){
					infopad.errs("该客户自己资源中有记录，请勿重复填写。",1,true);
					$("#btnSubmit").attr("disabled","disabled");
					$(".off_input").attr("readonly",true);
					
					if(type=="phone"){
						$("#"+type).parent().parent().find( "p[rel='errnote']").html("该客户自己资源中有记录，请勿重复填写。");
					}else{
						$("#"+type).parent().find( "p[rel='errnote']").html("该客户自己资源中有记录，请勿重复填写。");
					}
					
					$("#"+type).attr("readonly",false);
				}else{
					infopad.errs("该客户资源已经进行登记，归属人-"+name+"。",1,true);
					$("#btnSubmit").attr("disabled","disabled");
					$(".off_input").attr("readonly",true);
					if(type=="phone"){
						$("#"+type).parent().parent().find( "p[rel='errnote']").html("该客户资源已经进行登记，归属人 - "+name+"。");
					}else{
						$("#"+type).parent().find( "p[rel='errnote']").html("该客户资源已经进行登记，归属人-"+name+"。");
					}
					
					$("#"+type).attr("readonly",false);
					}
				}else{
						$( "#__INFO_PAD" ).hide();
						$("#btnSubmit").attr("disabled",false);
						$(".off_input").attr("readonly",false);
				}
			}, "json" );
		}



function quest_phone( tar )
{
	var quests = [];
	var i=0;
	tar.find( "p[rel='QUEST_PHONE']" ).each( function()
	{
		var phone = $( this ).find( "input[name='phone']" ) .val();
		//正则验证手机号码
		if(phone !== ""){
			if(!(/^1[0-9]{10}$/.test(phone))){
				alert("输入的手机号码有误，请重新输入！");
				return false;
			}
		}
		pho = phone;
		var name = $("input[name='myrad"+i+"']:checked").val();
		var guanxi = $( this ).find( "input[name='guanxi']" ).val();
		
		quests.push( {
			phone: phone,
			name: name,
			guanxi:guanxi
		} );
		i++;
	} );
	
	return quests;
}

function submit_form()
{
	var data = {};
	// 客户资料
	data.nickname = $( "#nickname" ).val();
	data.keyname = $( "#keyname" ).val();
	data.invalid = $( "#invalid" ).prop( "checked" ) ? 1 : 0;
	data.category = $( "#category" ).val();
	data.source = $( "#source" ).val();
	data.url = $( "#url" ).val();
	data.keyword = $( "#keyword" ).val();
	data.quests = JSON.stringify( quest_collect( $( "#quest_list" ) ) );
	data.allPhone = JSON.stringify( quest_phone( $( "#allPhone" ) ) );
	data.province = $( "#province" ).val();
	data.city = $( "#city" ).val();
	data.address = $( "#address" ).val();
	data.phone = $( "#phone" ).val();
	data.email = $( "#email" ).val();
	data.weixin = $( "#weixin" ).val();
	data.qq = $( "#qq" ).val();
	data.ip = $( "#ip" ).val();
	data.intention = $( "#intention" ).val();
	data.desc = $( "#desc" ).html();
	data.laiYuanUrl = $( "#laiYuanUrl" ).val();
	
	if(data.province == null || data.province == ""){
		 infopad.err( "请选择省份!" );
		 return false;
	}
	
	if(data.city == null || data.city == ""){
		 infopad.err( "请选择城市!" );
		 return false;
	}
	
	if(data.laiYuanUrl == null || data.laiYuanUrl == ""){
		 infopad.err( "初始访问网址不能为空!" );
		 return false;
	}
	
	if(data.source == null || data.source == ""){
		 infopad.err( "请选择来源渠道!" );
		 return false;
	}
	
	//验证联系方式
	if(pho=="" && data.email== ""  && data.weixin=="" && data.qq=="" && data.phone==""){
		infopad.err("请至少填写一种联系方式。");
		return false;
	}
	
	if(data.invalid == 1 && data.desc == ""){
		infopad.err("请在备注信息填写无效的原因。");
		 return false;
	}
	
	// 跟踪数据
	data.remark = $( "#remark" ).html();
	data.protime = $("#proTime").val();
	data.target = $("#target").val();
	var states = [];

  	$( "#statelist input:checked" ).each( function(){
		var val = $( this ).attr( "value" );
		states.push( val );
	} );
	
	data.states = states.join( "," );
	if((data.states).indexOf("138g5wfwm1mx")>=0 && data.protime ==""){
		alert("请设置定时提醒的时间。");
		return false;
	}
	if((data.states).indexOf("o3dpi9gzuol4")>=0 && data.target ==""){
		alert("请设置转交老师。");
		return false;
	}

	// 学员数据
	var student = get_students();
	data.student = JSON.stringify( student );
	$("#btnSubmit").attr("disabled","disabled");
	submitter.post( contextPath+"/index/addConsultant_client_first.json", data, function( d )
	{
		location.reload();
		if( d.err == 0 )
		{
			infopad.msg( d.msg );
			location.reload();
		}
		else
		{
			//infopad.err( d.msg, d.delay );
		}
	}, "json" );
}

//--------------------------------------------------------------------------
//
//	methods
//
//--------------------------------------------------------------------------

function bodyKeyupHandler( e )
{
	if( e.ctrlKey && e.which == 13 )
	{
		submit_form();
	}
	else
		if( e.ctrlKey && e.shiftKey && e.which == 70 )// ctrl+shift+f
		{
			var edt = $( document.activeElement );
			var id = edt.attr( "id" );

			if( _editor.indexOf( id ) > -1 )
			{
				edt.html( htmlfilter( edt.html() ) );
			}
		}
}
